#include <QLogger>

QString QLogger::TimeStamp =
    QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss");
QString QLogger::mLogSavePath = ".";

std::shared_ptr<spdlog::sinks::stdout_color_sink_mt> QLogger::ConsoleSink;
std::shared_ptr<spdlog::sinks::basic_file_sink_mt> QLogger::FileSink;

bool QLogger::isInit = false;

void QLogger::checkInit() {
  if (!isInit) {
    spdlog::error("QLogger need run QLogger::init() first!");
    throw "QLogger need run QLogger::init() first!";
  }
  return;
}

QLogger::QLogger(const QString &name, const LogModes &modes, QObject *parent)
    : QObject(parent) {
  std::vector<spdlog::sink_ptr> sinks;
  if (modes.testFlag(Console)) {
    sinks.push_back(ConsoleSink);
  }
  if (modes.testFlag(File)) {
    sinks.push_back(FileSink);
  }
  mLogger = new spdlog::logger(name.toStdString(), sinks.begin(), sinks.end());
  mLogger->flush_on(spdlog::level::info);
  mLogger->set_level(spdlog::level::debug);
}

QLogger::~QLogger() { delete mLogger; }

void QLogger::setSavePath(const QString &path) { mLogSavePath = path; }
void QLogger::setModeLevel(const Level &level, const LogModes &modes) {
  if (modes.testFlag(Console)) {
    ConsoleSink->set_level(level);
  }
  if (modes.testFlag(File)) {
    FileSink->set_level(level);
  }
}

// Global Init()
// Set file dir for saving before init()
void QLogger::init() {
  if (isInit) {
    spdlog::warn("Repeat init");
    return;
  }
  ConsoleSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
  QString filename = mLogSavePath + "/" + TimeStamp + ".log";
  FileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(
      filename.toStdString(), true);

  isInit = true;
}

void QLogger::setLevel(const Level &level) { mLogger->set_level(level); }

void QLogger::error(const QString &mesg) {
  checkInit();
  mLogger->error(mesg.toStdString());
}
void QLogger::info(const QString &mesg) {
  checkInit();
  mLogger->info(mesg.toStdString());
}
void QLogger::warn(const QString &mesg) {
  checkInit();
  mLogger->warn(mesg.toStdString());
}
void QLogger::debug(const QString &mesg) {
  checkInit();
  mLogger->debug(mesg.toStdString());
}
